package com.hadluo.qq.client.ui;

import com.formdev.flatlaf.FlatDarkLaf;
import com.hadluo.qq.client.event.MessageEvent;
import com.hadluo.qq.client.event.UserStatusEvent;
import com.hadluo.qq.client.model.*;
import com.hadluo.qq.client.utils.Constants;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.client.utils.HttpClient;
import com.hadluo.qq.client.websocket.QQWebSocketClient;
import java.awt.event.MouseEvent;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Timer;

/**
 * QQ主窗口
 * @author hadluo
 */
public class MainFrame extends JFrame implements ProfileDialog.ProfileUpdateListener,
        com.hadluo.qq.client.websocket.QQWebSocketClient.UserStatusListener,
        com.hadluo.qq.client.websocket.QQWebSocketClient.MessageListener {

    @Override
    public void onProfileUpdated(UserInfo updatedUserInfo) {
        // 更新本地用户信息
        this.userInfo = updatedUserInfo;

        // 重新获取最新的用户信息并更新界面
        new Thread(() -> {
            try {
                UserInfo latestInfo = HttpClient.getUserInfo(userInfo.getQqNumber()).getUserInfo();
                if (latestInfo != null) {
                    SwingUtilities.invokeLater(() -> {
                        this.userInfo = latestInfo;
                        updateUserInfoDisplay(); // 更新界面显示
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void updateUserInfoDisplay() {
        // 设置用户头像
        if (userInfo != null && userInfo.getAvatar() != null && !userInfo.getAvatar().isEmpty()) {
            nicknameLabel.setText(userInfo.getNickname());
            try {
                String avatarUrl = userInfo.getAvatar();
                // 确保URL包含完整的服务器地址前缀
                if (!avatarUrl.startsWith("http")) {
                    avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                }
                ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                Image image = imageIcon.getImage().getScaledInstance(60, 60, Image.SCALE_SMOOTH);
                avatarLabel.setIcon(new ImageIcon(image));
            } catch (Exception e) {
                e.printStackTrace();
                // 如果加载失败，显示默认头像
                avatarLabel.setText(userInfo.getNickname().substring(0, 1));
                avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
            }
        } else {
            // 如果没有头像，显示昵称首字
            avatarLabel.setText(userInfo.getNickname().substring(0, 1));
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
            avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        }
    }

    @Override
    public void onMessageReceived(MessageEvent event) {
        SwingUtilities.invokeLater(() -> {
            Message message = event.getMessage();
            if (message != null) {
                // 来私聊消息了
                // 更新好友列表中的最后一条消息
                for (int i = 0; i < friendListModel.size(); i++) {
                    FriendListItem item = friendListModel.getElementAt(i);
                    if (item.getQqNumber().equals(String.valueOf(message.getSenderId()))) {
                        item.setLastMessage(message.getContent());
                        item.setLastMessageTime(message.getCreateTime().getTime());
                        item.markNewMessage(); // 标记为未读消息
                        friendList.repaint();
                        break;
                    }
                }

                // 更新常用联系人列表中的最后一条消息
                for (int i = 0; i < favoriteListModel.size(); i++) {
                    FavoriteListItem item = favoriteListModel.getElementAt(i);
                    if (item.getQqNumber().equals(String.valueOf(message.getSenderId()))) {
                        item.setLastMessage(message.getContent());
                        item.setLastMessageTime(message.getCreateTime().getTime());
                        item.markNewMessage(); // 标记为未读消息
                        favoriteList.repaint();
                        break;
                    }
                }
            }
            // 来群消息了
            GroupMessage groupMessage = event.getGroupMessage();
            if (groupMessage != null) {
                groupListPanel.onMessageReceived(groupMessage);
            }
            // 播放提示音
            Toolkit.getDefaultToolkit().beep();
        });
    }

    private JList<FriendListItem> friendList;
    private DefaultListModel<FriendListItem> friendListModel;
    private JTextField searchField;
    private JPanel contentPanel;
    private CardLayout cardLayout;
    private UserInfo userInfo;
    private JLabel avatarLabel;
    private JButton friendListButton;
    private JButton favoriteListButton;
    private JButton addFriendButton;
    private JButton groupListButton;
    private JButton createGroupButton;
    private GroupListPanel groupListPanel;
    private JLabel nicknameLabel;
    private JList<FavoriteListItem> favoriteList;
    private DefaultListModel<FavoriteListItem> favoriteListModel;
    private JPanel favoriteListPanel;

    public MainFrame(UserInfo userInfo) {
        this.userInfo = userInfo;
        QQWebSocketClient.connect(userInfo);
        QQWebSocketClient.getInstance().addStatusListener(this);
        QQWebSocketClient.getInstance().addMessageListener(this);
        initializeUI();

        updateUserInfoDisplay();
    }

    private void initializeUI() {
        // 设置窗口基本属性
        setTitle("Chat");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 600);
        setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(35, 35, 35));

        // 创建左侧功能区面板
        JPanel functionPanel = createFunctionPanel();
        functionPanel.setPreferredSize(new Dimension(80, 0));

        // 创建右侧内容区
        contentPanel = new JPanel(new CardLayout());
        cardLayout = (CardLayout) contentPanel.getLayout();

        // 添加好友列表面板到内容区
        JPanel friendListPanel = createFriendListPanel();
        contentPanel.add(friendListPanel, "friendList");

        // 添加常用联系人列表面板到内容区
        favoriteListPanel = createFavoriteListPanel();
        contentPanel.add(favoriteListPanel, "favoriteList");

        // 添加群列表面板到内容区
        groupListPanel = new GroupListPanel(userInfo);
        contentPanel.add(groupListPanel, "groupList");

        // 添加好友列表右键菜单
        JPopupMenu friendPopupMenu = createFriendPopupMenu();
        friendList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    FriendListItem selectedFriend = friendList.getSelectedValue();
                    if (selectedFriend != null) {
                        openChatPanel(selectedFriend);
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopupMenu(e, friendPopupMenu);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopupMenu(e, friendPopupMenu);
                }
            }

            private void showPopupMenu(MouseEvent e, JPopupMenu popupMenu) {
                int index = friendList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    friendList.setSelectedIndex(index);
                    popupMenu.show(friendList, e.getX(), e.getY());
                }
            }
        });

        // 添加常用联系人列表右键菜单
        JPopupMenu favoritePopupMenu = createFavoritePopupMenu();
        favoriteList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    FavoriteListItem selectedFavorite = favoriteList.getSelectedValue();
                    if (selectedFavorite != null) {
                        openChatPanel(selectedFavorite);
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopupMenu(e, favoritePopupMenu);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopupMenu(e, favoritePopupMenu);
                }
            }

            private void showPopupMenu(MouseEvent e, JPopupMenu popupMenu) {
                int index = favoriteList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    favoriteList.setSelectedIndex(index);
                    popupMenu.show(favoriteList, e.getX(), e.getY());
                }
            }
        });

        // 添加分隔面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, functionPanel, contentPanel);
        splitPane.setDividerLocation(80);
        splitPane.setDividerSize(1);
        splitPane.setBorder(null);

        mainPanel.add(splitPane);
        setContentPane(mainPanel);
    }

    private JPopupMenu createFriendPopupMenu() {
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem viewInfoItem = new JMenuItem("查看好友信息");
        JMenuItem removeFriendItem = new JMenuItem("移除好友");
        JMenuItem addFavoriteItem = new JMenuItem("设为常用联系人");

        viewInfoItem.addActionListener(e -> {
            FriendListItem selectedFriend = friendList.getSelectedValue();
            if (selectedFriend != null) {
                handleViewFriendInfo(selectedFriend);
            }
        });

        removeFriendItem.addActionListener(e -> {
            FriendListItem selectedFriend = friendList.getSelectedValue();
            if (selectedFriend != null) {
                handleRemoveFriend(selectedFriend);
            }
        });

        addFavoriteItem.addActionListener(e -> {
            FriendListItem selectedFriend = friendList.getSelectedValue();
            if (selectedFriend != null) {
                handleAddToFavorites(selectedFriend);
            }
        });


        popupMenu.add(viewInfoItem);
        popupMenu.add(removeFriendItem);
        popupMenu.add(addFavoriteItem);
        return popupMenu;
    }

    private JPopupMenu createFavoritePopupMenu() {
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem viewInfoItem = new JMenuItem("查看好友信息");
        JMenuItem removeFavoriteItem = new JMenuItem("移除常用联系人");

        viewInfoItem.addActionListener(e -> {
            FavoriteListItem selectedFavorite = favoriteList.getSelectedValue();
            if (selectedFavorite != null) {
                handleViewFavoriteInfo(selectedFavorite);
            }
        });

        removeFavoriteItem.addActionListener(e -> {
            FavoriteListItem selectedFavorite = favoriteList.getSelectedValue();
            if (selectedFavorite != null) {
                handleRemoveFavorite(selectedFavorite);
            }
        });

        popupMenu.add(viewInfoItem);
        popupMenu.add(removeFavoriteItem);
        return popupMenu;
    }

    private JPanel createFunctionPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(35, 35, 35));

        // 创建头像面板
        JPanel avatarPanel = new JPanel();
        avatarPanel.setLayout(new BoxLayout(avatarPanel, BoxLayout.Y_AXIS));
        avatarPanel.setBackground(new Color(35, 35, 35));
        avatarLabel = new JLabel();
        avatarLabel.setPreferredSize(new Dimension(60, 60));
        avatarLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        avatarLabel.setBorder(BorderFactory.createLineBorder(new Color(60, 60, 60)));
        avatarLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        avatarLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                ProfileDialog dialog = new ProfileDialog(MainFrame.this, userInfo, MainFrame.this);
                dialog.setVisible(true);
            }
        });
        avatarPanel.add(avatarLabel);
        avatarPanel.add(Box.createVerticalStrut(5));

        // 添加用户昵称标签
        nicknameLabel = new JLabel(userInfo.getNickname());
        nicknameLabel.setForeground(Color.WHITE);
        nicknameLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        nicknameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        nicknameLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        avatarPanel.add(nicknameLabel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
        buttonPanel.setBackground(new Color(35, 35, 35));

        friendListButton = createFunctionButton("好友列表");
        favoriteListButton = createFunctionButton("常用联系人列表");
        addFriendButton = createFunctionButton("添加好友");
        groupListButton = createFunctionButton("群列表");
        createGroupButton = createFunctionButton("建群");

        buttonPanel.add(Box.createVerticalStrut(20));
        buttonPanel.add(friendListButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(addFriendButton);
        buttonPanel.add(Box.createVerticalStrut(20));
        buttonPanel.add(favoriteListButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(groupListButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(createGroupButton);

        // 添加事件监听
        friendListButton.addActionListener(e -> showFriendList());
        addFriendButton.addActionListener(e -> handleAddFriend());
        favoriteListButton.addActionListener(e -> showFavoriteList());
        groupListButton.addActionListener(e -> showGroupList());
        createGroupButton.addActionListener(e -> handleCreateGroup());

        panel.add(avatarPanel, BorderLayout.NORTH);
        panel.add(buttonPanel, BorderLayout.CENTER);

        return panel;
    }

    private JButton createFunctionButton(String text) {
        JButton button = new JButton();
        button.setBackground(new Color(45, 45, 45));
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 60, 60)),
                BorderFactory.createEmptyBorder(8, 8, 8, 8)
        ));
        button.setMaximumSize(new Dimension(80, 60));
        button.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 设置图标
        try {
            String iconPath = "/icons/";
            switch (text) {
                case "好友列表":
                    iconPath += "friends.png";
                    break;
                case "添加好友":
                    iconPath += "add_friend.png";
                    break;
                case "常用联系人列表":
                    iconPath += "friends.png";
                    break;
                case "群列表":
                    iconPath += "group_list.png";
                    break;
                case "建群":
                    iconPath += "create_group.png";
                    break;
            }
            ImageIcon icon = new ImageIcon(getClass().getResource(iconPath));
            Image img = icon.getImage().getScaledInstance(24, 24, Image.SCALE_SMOOTH);
            button.setIcon(new ImageIcon(img));
        } catch (Exception e) {
            // 如果图标加载失败，使用文字
            button.setText(text);
        }

        // 设置鼠标悬停提示
        button.setToolTipText(text);

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(55, 55, 55));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(45, 45, 45));
            }
        });

        return button;
    }

    private JPanel createFriendListPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(35, 35, 35));

        // 创建个性签名面板
        JPanel signaturePanel = new JPanel(new BorderLayout());
        signaturePanel.setBackground(new Color(35, 35, 35));
        signaturePanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建个性签名标签
        String signature = userInfo.getSignature();
        if (signature == null || signature.trim().isEmpty()) {
            signature = "这个人很懒，什么都没留下";
        }
        JLabel signatureLabel = new JLabel("好友列表");
        signatureLabel.setForeground(Color.WHITE);
        signatureLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

        signaturePanel.add(signatureLabel, BorderLayout.CENTER);

        // 创建好友列表
        friendListModel = new DefaultListModel<>();
        friendList = new JList<>(friendListModel);
        friendList.setBackground(new Color(35, 35, 35));
        friendList.setForeground(Color.WHITE);
        friendList.setSelectionBackground(new Color(45, 45, 45));
        friendList.setSelectionForeground(new Color(29, 185, 84));
        friendList.setBorder(null);
        friendList.setCellRenderer(new FriendListCellRenderer());

        // 添加测试数据
        addTestData();

        JScrollPane scrollPane = new JScrollPane(friendList);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(29, 185, 84);
                this.trackColor = new Color(45, 45, 45);
            }
        });

        panel.add(signaturePanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createFavoriteListPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(new Color(35, 35, 35));

        // 创建个性签名面板
        JPanel signaturePanel = new JPanel(new BorderLayout());
        signaturePanel.setBackground(new Color(35, 35, 35));
        signaturePanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建个性签名标签
        JLabel signatureLabel = new JLabel("常用联系人列表");
        signatureLabel.setForeground(Color.WHITE);
        signatureLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

        signaturePanel.add(signatureLabel, BorderLayout.CENTER);

        // 创建常用联系人列表
        favoriteListModel = new DefaultListModel<>();
        favoriteList = new JList<>(favoriteListModel);
        favoriteList.setBackground(new Color(35, 35, 35));
        favoriteList.setForeground(Color.WHITE);
        favoriteList.setSelectionBackground(new Color(45, 45, 45));
        favoriteList.setSelectionForeground(new Color(29, 185, 84));
        favoriteList.setBorder(null);
        favoriteList.setCellRenderer(new FavoriteListCellRenderer());

        // 添加测试数据
        addFavoriteTestData();

        JScrollPane scrollPane = new JScrollPane(favoriteList);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(29, 185, 84);
                this.trackColor = new Color(45, 45, 45);
            }
        });

        panel.add(signaturePanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private void showFriendList() {
        cardLayout.show(contentPanel, "friendList");
        friendListButton.setBackground(new Color(55, 55, 55));
        favoriteListButton.setBackground(new Color(45, 45, 45));
    }

    private void showFavoriteList() {
        cardLayout.show(contentPanel, "favoriteList");
        favoriteListButton.setBackground(new Color(55, 55, 55));
        friendListButton.setBackground(new Color(45, 45, 45));
        refreshFavoriteList(); // 刷新常用联系人列表
    }

    private void showGroupList() {
        cardLayout.show(contentPanel, "groupList");
        groupListButton.setBackground(new Color(55, 55, 55));
        friendListButton.setBackground(new Color(45, 45, 45));
        groupListPanel.refreshGroupList();
    }

    private void handleCreateGroup() {
        CreateGroupDialog dialog = new CreateGroupDialog(this, userInfo);
        dialog.setVisible(true);
    }

    private void handleAddFriend() {
        String friendQQNumber = JOptionPane.showInputDialog(this,
                "请输入好友QQ号：",
                "添加好友",
                JOptionPane.PLAIN_MESSAGE);

        if (friendQQNumber != null && !friendQQNumber.trim().isEmpty()) {
            // 禁用添加好友按钮，防止重复点击
            addFriendButton.setEnabled(false);

            // 在新线程中执行添加好友请求
            new Thread(() -> {
                try {
                    // 发送添加好友请求
                    String url = "http://"+Constants.SERVER_HOST+":8080/api/friend/add";
                    JSONObject requestJson = new JSONObject();
                    requestJson.put("qqNumber", userInfo.getQqNumber());
                    requestJson.put("friendQQNumber", friendQQNumber);

                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setDoOutput(true);

                    try (OutputStream os = conn.getOutputStream()) {
                        byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                        os.write(input, 0, input.length);
                    }

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            boolean success = jsonResponse.getBoolean("success");
                            String message = jsonResponse.getString("message");

                            SwingUtilities.invokeLater(() -> {
                                if (success) {
                                    JOptionPane.showMessageDialog(this,
                                            "添加好友成功",
                                            "成功",
                                            JOptionPane.INFORMATION_MESSAGE);
                                    // 刷新好友列表
                                    refreshFriendList();
                                } else {
                                    JOptionPane.showMessageDialog(this,
                                            message,
                                            "添加失败",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                                addFriendButton.setEnabled(true);
                            });
                        }
                    } else {
                        throw new Exception("服务器响应错误: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this,
                                "添加好友失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        addFriendButton.setEnabled(true);
                    });
                }
            }).start();
        }
    }

    @Override
    public void onStatusChanged(UserStatusEvent event) {
        SwingUtilities.invokeLater(() -> {
            for (int i = 0; i < friendListModel.size(); i++) {
                FriendListItem item = friendListModel.getElementAt(i);
                if (item.getQqNumber().equals(event.getUserId())) {
                    item.setOnline(event.isOnline());
                    friendList.repaint();
                    break;
                }
            }

            for (int i = 0; i < favoriteListModel.size(); i++) {
                FavoriteListItem item = favoriteListModel.getElementAt(i);
                if (item.getQqNumber().equals(event.getUserId())) {
                    item.setOnline(event.isOnline());
                    favoriteList.repaint();
                    break;
                }
            }
        });
    }

    private void refreshFriendList() {
        // 发送获取好友列表请求
        new Thread(() -> {
            int maxRetries = 3;
            int retryCount = 0;
            boolean success = false;

            while (!success && retryCount < maxRetries) {
                try {
                    String url = "http://"+Constants.SERVER_HOST+":8080/api/friend/list?qqNumber=" + userInfo.getQqNumber();
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000); // 设置连接超时
                    conn.setReadTimeout(5000);    // 设置读取超时

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            if (jsonResponse.getBoolean("success")) {
                                JSONArray friends = jsonResponse.getJSONArray("data");
                                SwingUtilities.invokeLater(() -> {
                                    // 保存现有的消息记录
                                    Map<String, FriendListItem> existingItems = new HashMap<>();
                                    for (int i = 0; i < friendListModel.size(); i++) {
                                        FriendListItem item = friendListModel.getElementAt(i);
                                        existingItems.put(item.getQqNumber(), item);
                                    }

                                    friendListModel.clear();
                                    for (int i = 0; i < friends.size(); i++) {
                                        JSONObject friend = friends.getJSONObject(i);
                                        String qqNumber = friend.getString("qqNumber");

                                        // 如果存在现有的好友项，保留其消息记录
                                        FriendListItem existingItem = existingItems.get(qqNumber);
                                        FriendListItem newItem;

                                        if (existingItem != null) {
                                            newItem = new FriendListItem(qqNumber, friend.getString("nickname"));
                                            newItem.setAvatar(friend.getString("avatar"));
                                            newItem.setLastMessage(existingItem.getLastMessage());
                                            newItem.setLastMessageTime(existingItem.getLastMessageTime());
                                            newItem.setOnline(friend.getIntValue("status") == 1);
                                            newItem.setHasUnreadMessage(existingItem.hasUnreadMessage()); // 保留未读消息状态
                                            newItem.setSignature(friend.getString("signature")); // 设置个性签名
                                        } else {
                                            newItem = new FriendListItem(qqNumber, friend.getString("nickname"));
                                            newItem.setAvatar(friend.getString("avatar"));
                                            newItem.setLastMessage(friend.getString("lastMessage"));
                                            newItem.setLastMessageTime(friend.getLongValue("lastMessageTime"));
                                            newItem.setOnline(friend.getIntValue("status") == 1);
                                            newItem.setSignature(friend.getString("signature")); // 设置个性签名
                                        }
                                        friendListModel.addElement(newItem);
                                    }
                                });
                                success = true; // 标记成功
                            }
                        }
                    } else {
                        throw new Exception("服务器响应错误: " + responseCode);
                    }
                } catch (Exception e) {
                    retryCount++;
                    if (retryCount < maxRetries) {
                        try {
                            // 等待一段时间后重试
                            Thread.sleep(1000 * retryCount);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    } else {
                        e.printStackTrace();
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(MainFrame.this,
                                    "刷新好友列表失败，请稍后重试",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                        });
                    }
                }
            }
        }).start();
    }

    private void refreshFavoriteList() {
        new Thread(() -> {
            int maxRetries = 3;
            int retryCount = 0;
            boolean success = false;

            while (!success && retryCount < maxRetries) {
                try {
                    String url = "http://"+Constants.SERVER_HOST+":8080/api/favorites/list?qqNumber=" + userInfo.getQqNumber();
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            System.out.println("获取的常用联系人数据: " + response.toString());

                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            if (jsonResponse.getBoolean("success")) {
                                JSONArray favorites = jsonResponse.getJSONArray("data");
                                SwingUtilities.invokeLater(() -> {
                                    // 保存现有的消息记录
                                    Map<String, FavoriteListItem> existingItems = new HashMap<>();
                                    for (int i = 0; i < favoriteListModel.size(); i++) {
                                        FavoriteListItem item = favoriteListModel.getElementAt(i);
                                        existingItems.put(item.getQqNumber(), item);
                                    }

                                    favoriteListModel.clear();
                                    for (int i = 0; i < favorites.size(); i++) {
                                        JSONObject favorite = favorites.getJSONObject(i);

                                        // 使用正确的字段名
                                        String qqNumber = favorite.getString("qqNumber");
                                        String nickname = favorite.getString("nickname");

                                        System.out.println("处理常用联系人: " + qqNumber + ", 昵称: " + nickname);

                                        // 如果存在现有的好友项，保留其消息记录
                                        FavoriteListItem existingItem = existingItems.get(qqNumber);
                                        FavoriteListItem newItem;

                                        if (existingItem != null) {
                                            newItem = new FavoriteListItem(qqNumber, nickname);
                                            newItem.setAvatar(getSafeString(favorite, "avatar"));
                                            newItem.setLastMessage(existingItem.getLastMessage());
                                            newItem.setLastMessageTime(existingItem.getLastMessageTime());
                                            newItem.setOnline(existingItem.isOnline());
                                            newItem.setHasUnreadMessage(existingItem.hasUnreadMessage());
                                            newItem.setSignature(getSafeString(favorite, "signature"));
                                        } else {
                                            newItem = new FavoriteListItem(qqNumber, nickname);
                                            newItem.setAvatar(getSafeString(favorite, "avatar"));
                                            newItem.setLastMessage(getSafeString(favorite, "lastMessage"));
                                            newItem.setLastMessageTime(getSafeLong(favorite, "lastMessageTime"));
                                            newItem.setOnline(getSafeBoolean(favorite, "status"));
                                            newItem.setSignature(getSafeString(favorite, "signature"));
                                        }
                                        favoriteListModel.addElement(newItem);
                                    }
                                });
                                success = true;
                            } else {
                                System.out.println("服务器返回失败: " + jsonResponse.getString("message"));
                            }
                        }
                    } else {
                        throw new Exception("服务器响应错误: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    retryCount++;
                    if (retryCount < maxRetries) {
                        try {
                            Thread.sleep(1000 * retryCount);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    } else {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(MainFrame.this,
                                    "刷新常用联系人列表失败，请稍后重试",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                        });
                    }
                }
            }
        }).start();
    }
    // 安全获取字符串值，避免null异常
    // 安全获取字符串值
    private String getSafeString(JSONObject obj, String key) {
        String value = obj.getString(key);
        return value != null ? value : "";
    }

    // 安全获取长整型值
    private long getSafeLong(JSONObject obj, String key) {
        Object value = obj.get(key);
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        return 0;
    }

    // 安全获取布尔型状态值
    private boolean getSafeBoolean(JSONObject obj, String key) {
        Object value = obj.get(key);
        if (value instanceof Number) {
            return ((Number) value).intValue() == 1;
        }
        return false;
    }
    private void handleRemoveFriend(FriendListItem selectedFriend) {
        // 显示确认对话框
        int result = JOptionPane.showConfirmDialog(this,
                "确定要删除该好友吗？",
                "删除好友",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            // 禁用好友列表，防止重复操作
            friendList.setEnabled(false);

            // 在新线程中执行删除好友请求
            new Thread(() -> {
                try {
                    // 发送删除好友请求
                    String url = "http://"+Constants.SERVER_HOST+":8080/api/friend/delete?userQQNumber=" +
                            userInfo.getQqNumber() + "&friendQQNumber=" + selectedFriend.getQqNumber();

                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("DELETE");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            boolean success = jsonResponse.getBoolean("success");
                            String message = jsonResponse.getString("message");

                            SwingUtilities.invokeLater(() -> {
                                if (success) {
                                    JOptionPane.showMessageDialog(this,
                                            "删除好友成功",
                                            "成功",
                                            JOptionPane.INFORMATION_MESSAGE);
                                    // 刷新好友列表
                                    refreshFriendList();
                                } else {
                                    JOptionPane.showMessageDialog(this,
                                            message,
                                            "删除失败",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                                friendList.setEnabled(true);
                            });
                        }
                    } else {
                        throw new Exception("服务器响应错误: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this,
                                "删除好友失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        friendList.setEnabled(true);
                    });
                }
            }).start();
        }
    }

    private void handleRemoveFavorite(FavoriteListItem selectedFavorite) {
        // 显示确认对话框
        int result = JOptionPane.showConfirmDialog(this,
                "确定要移除该常用联系人吗？",
                "移除常用联系人",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            // 禁用常用联系人列表，防止重复操作
            favoriteList.setEnabled(false);

            // 在新线程中执行移除常用联系人请求
            new Thread(() -> {
                try {
                    // 发送移除常用联系人请求
                    String url = "http://"+Constants.SERVER_HOST+":8080/api/favorites/delete?userQQNumber=" +
                            userInfo.getQqNumber() + "&friendQQNumber=" + selectedFavorite.getQqNumber();

                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("DELETE");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        try (BufferedReader br = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                            StringBuilder response = new StringBuilder();
                            String responseLine;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }

                            JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                            boolean success = jsonResponse.getBoolean("success");
                            String message = jsonResponse.getString("message");

                            SwingUtilities.invokeLater(() -> {
                                if (success) {
                                    JOptionPane.showMessageDialog(this,
                                            "移除常用联系人成功",
                                            "成功",
                                            JOptionPane.INFORMATION_MESSAGE);
                                    // 刷新常用联系人列表
                                    refreshFavoriteList();
                                } else {
                                    JOptionPane.showMessageDialog(this,
                                            message,
                                            "移除失败",
                                            JOptionPane.ERROR_MESSAGE);
                                }
                                favoriteList.setEnabled(true);
                            });
                        }
                    } else {
                        throw new Exception("服务器响应错误: " + responseCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this,
                                "移除常用联系人失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        favoriteList.setEnabled(true);
                    });
                }
            }).start();
        }
    }

    private void openChatPanel(FriendListItem friend) {
        // 创建并显示聊天窗口
        ChatFrame chatFrame = new ChatFrame(friend, userInfo);
        chatFrame.setVisible(true);
    }

    private void openChatPanel(FavoriteListItem favorite) {
        // 创建并显示聊天窗口
        FriendListItem friend=new FriendListItem(favorite);
        ChatFrame chatFrame = new ChatFrame(friend, userInfo);
        chatFrame.setVisible(true);
    }

    private void handleViewFriendInfo(FriendListItem selectedFriend) {
        // 禁用查看信息功能，防止重复点击
        friendList.setEnabled(false);

        // 在新线程中执行获取好友信息请求
        new Thread(() -> {
            try {
                // 发送获取好友信息请求
                String url = "http://"+Constants.SERVER_HOST+":8080/api/friend/detail?userQQNumber=" + userInfo.getQqNumber() +
                        "&friendQQNumber=" + selectedFriend.getQqNumber();

                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                        if (jsonResponse.getBoolean("success")) {
                            JSONObject friendInfo = jsonResponse.getJSONObject("data");

                            // 在EDT中显示好友信息对话框
                            SwingUtilities.invokeLater(() -> {
                                showFriendInfoDialog(friendInfo);
                            });
                        } else {
                            throw new Exception(jsonResponse.getString("message"));
                        }
                    }
                } else {
                    throw new Exception("服务器响应错误: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(MainFrame.this,
                            "获取好友信息失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            } finally {
                SwingUtilities.invokeLater(() -> {
                    friendList.setEnabled(true);
                });
            }
        }).start();
    }

    private void handleViewFavoriteInfo(FavoriteListItem selectedFavorite) {
        // 禁用查看信息功能，防止重复点击
        favoriteList.setEnabled(false);

        // 在新线程中执行获取好友信息请求
        new Thread(() -> {
            try {
                // 发送获取好友信息请求
                String url = "http://"+Constants.SERVER_HOST+":8080/api/friend/detail?userQQNumber=" + userInfo.getQqNumber() +
                        "&friendQQNumber=" + selectedFavorite.getQqNumber();

                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                        if (jsonResponse.getBoolean("success")) {
                            JSONObject friendInfo = jsonResponse.getJSONObject("data");

                            // 在EDT中显示好友信息对话框
                            SwingUtilities.invokeLater(() -> {
                                showFriendInfoDialog(friendInfo);
                            });
                        } else {
                            throw new Exception(jsonResponse.getString("message"));
                        }
                    }
                } else {
                    throw new Exception("服务器响应错误: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(MainFrame.this,
                            "获取好友信息失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            } finally {
                SwingUtilities.invokeLater(() -> {
                    favoriteList.setEnabled(true);
                });
            }
        }).start();
    }

    private void showFriendInfoDialog(JSONObject friendInfo) {
        // 创建一个自定义对话框
        JDialog dialog = new JDialog(this, "好友信息", true);
        dialog.setSize(350, 400);
        dialog.setLocationRelativeTo(this);

        // 创建内容面板
        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
        contentPanel.setBackground(new Color(35, 35, 35));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 添加头像
        JLabel avatarLabel = new JLabel();
        avatarLabel.setPreferredSize(new Dimension(140, 140));
        avatarLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 60, 60), 2),
                BorderFactory.createEmptyBorder(4, 4, 4, 4)
        ));
        avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);

        String avatarUrl = friendInfo.getString("avatar");
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            try {
                if (!avatarUrl.startsWith("http")) {
                    avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                }
                ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                Image image = imageIcon.getImage().getScaledInstance(130, 130, Image.SCALE_SMOOTH);
                avatarLabel.setIcon(new ImageIcon(image));
            } catch (Exception e) {
                avatarLabel.setText(friendInfo.getString("nickname").substring(0, 1));
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 54));
                avatarLabel.setForeground(Color.WHITE);
            }
        }

        // 设置头像位置
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        contentPanel.add(avatarLabel, gbc);

        // 添加昵称和在线状态
        JPanel nicknamePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 12, 0));
        nicknamePanel.setOpaque(false);

        JLabel nicknameLabel = new JLabel(friendInfo.getString("nickname"));
        nicknameLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        nicknameLabel.setForeground(Color.WHITE);

        JLabel statusIndicator = new JLabel();
        statusIndicator.setPreferredSize(new Dimension(14, 14));
        statusIndicator.setOpaque(true);
        Integer status = friendInfo.getInteger("status");
        if (status != null && status == 1) {
            statusIndicator.setBackground(new Color(29, 185, 84));
            statusIndicator.setToolTipText("在线");
        } else {
            statusIndicator.setBackground(new Color(153, 153, 153));
            statusIndicator.setToolTipText("离线");
        }

        nicknamePanel.add(nicknameLabel);
        nicknamePanel.add(statusIndicator);

        gbc.gridy = 1;
        gbc.insets = new Insets(20, 8, 8, 8);
        contentPanel.add(nicknamePanel, gbc);

        // 添加QQ号
        JLabel qqLabel = new JLabel("QQ：" + friendInfo.getString("qqNumber"));
        qqLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        qqLabel.setForeground(new Color(200, 200, 200));
        qqLabel.setHorizontalAlignment(SwingConstants.CENTER);
        gbc.gridy = 2;
        gbc.insets = new Insets(12, 8, 8, 8);
        contentPanel.add(qqLabel, gbc);

        // 添加个性签名
        String signature = friendInfo.getString("signature");
        if (signature == null || signature.trim().isEmpty()) {
            signature = "这个人很懒，什么都没留下";
        }

        JTextArea signatureArea = new JTextArea(signature);
        signatureArea.setEditable(false);
        signatureArea.setWrapStyleWord(true);
        signatureArea.setLineWrap(true);
        signatureArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        signatureArea.setForeground(new Color(180, 180, 180));
        signatureArea.setBackground(new Color(45, 45, 45));
        signatureArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(60, 60, 60)),
                BorderFactory.createEmptyBorder(12, 12, 12, 12)
        ));

        JScrollPane scrollPane = new JScrollPane(signatureArea);
        scrollPane.setPreferredSize(new Dimension(280, 90));
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUI(new BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(80, 80, 80);
                this.trackColor = new Color(45, 45, 45);
            }
        });

        gbc.gridy = 3;
        gbc.insets = new Insets(20, 8, 8, 8);
        contentPanel.add(scrollPane, gbc);

        dialog.add(contentPanel);
        dialog.setVisible(true);
    }

    private void addTestData() {
        // 初始化时刷新好友列表
        refreshFriendList();

        // 创建定时器，每30秒刷新一次好友列表
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                refreshFriendList();
            }
        }, 30000, 30000); // 延迟30秒，每30秒执行一次
    }

    private void addFavoriteTestData() {
        // 初始化时刷新常用联系人列表
        refreshFavoriteList();

        // 创建定时器，每30秒刷新一次常用联系人列表
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                refreshFavoriteList();
            }
        }, 30000, 30000); // 延迟30秒，每30秒执行一次
    }

    private void handleAddToFavorites(FriendListItem friend) {
        // 禁用按钮，防止重复点击
        addFriendButton.setEnabled(false);

        // 在新线程中执行添加常用联系人请求
        new Thread(() -> {
            try {
                // 发送添加常用联系人请求
                String url = "http://"+Constants.SERVER_HOST+":8080/api/favorites/add";
                JSONObject requestJson = new JSONObject();
                requestJson.put("qqNumber", userInfo.getQqNumber());
                requestJson.put("friendQQNumber", friend.getQqNumber());

                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);

                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }

                        JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                        boolean success = jsonResponse.getBoolean("success");
                        String message = jsonResponse.getString("message");

                        SwingUtilities.invokeLater(() -> {
                            if (success) {
                                JOptionPane.showMessageDialog(this,
                                        message,
                                        "成功",
                                        JOptionPane.INFORMATION_MESSAGE);
                                // 刷新好友列表和常用联系人列表
                                refreshFriendList();
                                refreshFavoriteList();
                            } else {
                                JOptionPane.showMessageDialog(this,
                                        message,
                                        "添加失败",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                            addFriendButton.setEnabled(true);
                        });
                    }
                } else {
                    throw new Exception("服务器响应错误: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                            "添加常用联系人失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                    addFriendButton.setEnabled(true);
                });
            }
        }).start();
    }

    // 好友列表项渲染器
    private class FriendListCellRenderer extends JPanel implements ListCellRenderer<FriendListItem> {
        private JPanel avatarPanel = new JPanel(new BorderLayout());
        private JLabel avatarLabel = new JLabel();
        private JLabel statusIndicator = new JLabel();
        private JLabel nicknameLabel = new JLabel();
        private JLabel messageLabel = new JLabel();
        private JLabel timeLabel = new JLabel();
        private JLabel unreadIndicator = new JLabel(); // 添加未读消息指示器
        private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");

        public FriendListCellRenderer() {
            setLayout(new BorderLayout(10, 5));
            setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
            setOpaque(true);

            // 创建左侧头像面板
            avatarPanel.setOpaque(false);
            avatarPanel.setPreferredSize(new Dimension(40, 40));
            avatarPanel.setLayout(null); // 使用绝对布局以便放置未读消息指示器

            // 设置头像标签
            avatarLabel.setPreferredSize(new Dimension(40, 40));
            avatarLabel.setBorder(BorderFactory.createLineBorder(new Color(60, 60, 60)));
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
            avatarLabel.setBounds(0, 0, 40, 40);
            avatarPanel.add(avatarLabel);

            // 设置未读消息指示器
            unreadIndicator.setPreferredSize(new Dimension(10, 10));
            unreadIndicator.setOpaque(true);
            unreadIndicator.setBackground(Color.RED);
            unreadIndicator.setBounds(30, 0, 10, 10); // 放置在头像右上角
            unreadIndicator.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
            avatarPanel.add(unreadIndicator);

            // 创建中间信息面板
            JPanel infoPanel = new JPanel(new BorderLayout());
            infoPanel.setOpaque(false);

            // 创建昵称面板（包含昵称和在线状态）
            JPanel nicknamePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
            nicknamePanel.setOpaque(false);
            nicknameLabel.setForeground(Color.WHITE);

            // 设置状态指示器
            statusIndicator.setPreferredSize(new Dimension(12, 12));
            statusIndicator.setOpaque(true);
            statusIndicator.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); // 添加上边距使其垂直对齐

            nicknamePanel.add(nicknameLabel);
            nicknamePanel.add(statusIndicator);

            // 设置消息标签
            messageLabel.setForeground(new Color(153, 153, 153));

            infoPanel.add(nicknamePanel, BorderLayout.NORTH);
            infoPanel.add(messageLabel, BorderLayout.CENTER);

            // 创建右侧时间面板
            timeLabel.setForeground(new Color(153, 153, 153));
            timeLabel.setHorizontalAlignment(SwingConstants.RIGHT);

            add(avatarPanel, BorderLayout.WEST);
            add(infoPanel, BorderLayout.CENTER);
            add(timeLabel, BorderLayout.EAST);
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends FriendListItem> list,
                                                      FriendListItem value, int index, boolean isSelected, boolean cellHasFocus) {
            // 设置头像
            if (value.getAvatar() != null && !value.getAvatar().isEmpty()) {
                try {
                    String avatarUrl = value.getAvatar();
                    if (!avatarUrl.startsWith("http")) {
                        avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                    }
                    URL url = new URL(avatarUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(3000);
                    connection.setReadTimeout(3000);

                    try (InputStream in = new BufferedInputStream(connection.getInputStream())) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while ((n = in.read(buf)) > 0) {
                            out.write(buf, 0, n);
                        }
                        byte[] response = out.toByteArray();
                        ImageIcon imageIcon = new ImageIcon(response);
                        Image image = imageIcon.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                        avatarLabel.setIcon(new ImageIcon(image));
                        avatarLabel.setText("");
                    }
                } catch (Exception e) {
                    // 如果加载失败，显示首字母
                    avatarLabel.setIcon(null);
                    avatarLabel.setText(value.getNickname().substring(0, 1));
                    avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
                    avatarLabel.setForeground(Color.WHITE);
                }
            } else {
                // 如果没有头像，显示首字母
                avatarLabel.setIcon(null);
                avatarLabel.setText(value.getNickname().substring(0, 1));
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
                avatarLabel.setForeground(Color.WHITE);
            }

            // 设置在线状态指示器
            if (value.isOnline()) {
                statusIndicator.setBackground(new Color(29, 185, 84)); // 在线-绿色
            } else {
                statusIndicator.setBackground(new Color(153, 153, 153)); // 离线-灰色
            }
            statusIndicator.setBorder(BorderFactory.createLineBorder(getBackground(), 2));
            statusIndicator.setToolTipText(value.isOnline() ? "在线" : "离线");

            nicknameLabel.setText(value.getNickname());
            messageLabel.setText(value.getLastMessage());

            // 格式化时间显示
            Date now = new Date();
            if (now.getTime() - value.getLastMessageTime() < 24 * 60 * 60 * 1000) {
                timeLabel.setText(timeFormat.format(value.getLastMessageTime()));
            } else {
                timeLabel.setText(dateFormat.format(value.getLastMessageTime()));
            }

            setBackground(isSelected ? new Color(45, 45, 45) : new Color(35, 35, 35));

            // 设置未读消息指示器的可见性
            unreadIndicator.setVisible(value.hasUnreadMessage());

            return this;
        }
    }

    // 常用联系人列表项渲染器
    // 常用联系人列表项渲染器
    private class FavoriteListCellRenderer extends JPanel implements ListCellRenderer<FavoriteListItem> {
        private JPanel avatarPanel = new JPanel(new BorderLayout());
        private JLabel avatarLabel = new JLabel();
        private JLabel statusIndicator = new JLabel();
        private JLabel nicknameLabel = new JLabel();
        private JLabel messageLabel = new JLabel();
        private JLabel timeLabel = new JLabel();
        private JLabel unreadIndicator = new JLabel(); // 添加未读消息指示器
        private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");

        public FavoriteListCellRenderer() {
            setLayout(new BorderLayout(10, 5));
            setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
            setOpaque(true);

            // 创建左侧头像面板
            avatarPanel.setOpaque(false);
            avatarPanel.setPreferredSize(new Dimension(40, 40));
            avatarPanel.setLayout(null); // 使用绝对布局以便放置未读消息指示器

            // 设置头像标签
            avatarLabel.setPreferredSize(new Dimension(40, 40));
            avatarLabel.setBorder(BorderFactory.createLineBorder(new Color(60, 60, 60)));
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
            avatarLabel.setBounds(0, 0, 40, 40);
            avatarPanel.add(avatarLabel);

            // 设置未读消息指示器
            unreadIndicator.setPreferredSize(new Dimension(10, 10));
            unreadIndicator.setOpaque(true);
            unreadIndicator.setBackground(Color.RED);
            unreadIndicator.setBounds(30, 0, 10, 10); // 放置在头像右上角
            unreadIndicator.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
            avatarPanel.add(unreadIndicator);

            // 创建中间信息面板
            JPanel infoPanel = new JPanel(new BorderLayout());
            infoPanel.setOpaque(false);

            // 创建昵称面板（包含昵称和在线状态）
            JPanel nicknamePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
            nicknamePanel.setOpaque(false);
            nicknameLabel.setForeground(Color.WHITE);

            // 设置状态指示器
            statusIndicator.setPreferredSize(new Dimension(12, 12));
            statusIndicator.setOpaque(true);
            statusIndicator.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); // 添加上边距使其垂直对齐

            nicknamePanel.add(nicknameLabel);
            nicknamePanel.add(statusIndicator);

            // 设置消息标签
            messageLabel.setForeground(new Color(153, 153, 153));

            infoPanel.add(nicknamePanel, BorderLayout.NORTH);
            infoPanel.add(messageLabel, BorderLayout.CENTER);

            // 创建右侧时间面板
            timeLabel.setForeground(new Color(153, 153, 153));
            timeLabel.setHorizontalAlignment(SwingConstants.RIGHT);

            add(avatarPanel, BorderLayout.WEST);
            add(infoPanel, BorderLayout.CENTER);
            add(timeLabel, BorderLayout.EAST);
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends FavoriteListItem> list,
                                                      FavoriteListItem value, int index, boolean isSelected, boolean cellHasFocus) {
            // 空值检查：确保value不为null
            if (value == null) {
                setBackground(isSelected ? new Color(45, 45, 45) : new Color(35, 35, 35));
                return this;
            }

            // 设置头像
            if (value.getAvatar() != null && !value.getAvatar().isEmpty()) {
                try {
                    String avatarUrl = value.getAvatar();
                    if (!avatarUrl.startsWith("http")) {
                        avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                    }
                    URL url = new URL(avatarUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(3000);
                    connection.setReadTimeout(3000);

                    try (InputStream in = new BufferedInputStream(connection.getInputStream())) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while ((n = in.read(buf)) > 0) {
                            out.write(buf, 0, n);
                        }
                        byte[] response = out.toByteArray();
                        ImageIcon imageIcon = new ImageIcon(response);
                        Image image = imageIcon.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                        avatarLabel.setIcon(new ImageIcon(image));
                        avatarLabel.setText("");
                    }
                } catch (Exception e) {
                    // 如果加载失败，显示首字母或默认文本
                    setDefaultAvatar(value);
                }
            } else {
                // 如果没有头像，显示首字母或默认文本
                setDefaultAvatar(value);
            }

            // 设置在线状态指示器
            if (value.isOnline()) {
                statusIndicator.setBackground(new Color(29, 185, 84)); // 在线-绿色
            } else {
                statusIndicator.setBackground(new Color(153, 153, 153)); // 离线-灰色
            }
            statusIndicator.setBorder(BorderFactory.createLineBorder(getBackground(), 2));
            statusIndicator.setToolTipText(value.isOnline() ? "在线" : "离线");

            // 设置昵称，添加空值处理
            nicknameLabel.setText(getSafeNickname(value));

            // 设置最后消息，添加空值处理
            messageLabel.setText(getSafeLastMessage(value));

            // 格式化时间显示，添加空值处理
            setTimeLabel(value);

            setBackground(isSelected ? new Color(45, 45, 45) : new Color(35, 35, 35));

            // 设置未读消息指示器的可见性
            unreadIndicator.setVisible(value.hasUnreadMessage());

            return this;
        }

        // 设置默认头像（处理昵称可能为null的情况）
        private void setDefaultAvatar(FavoriteListItem value) {
            avatarLabel.setIcon(null);
            String displayText = getSafeNickname(value);
            if (displayText != null && !displayText.isEmpty()) {
                avatarLabel.setText(displayText.substring(0, 1));
            } else {
                avatarLabel.setText("?");
            }
            avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
            avatarLabel.setForeground(Color.WHITE);
        }

        // 获取安全的昵称（处理null情况）
        private String getSafeNickname(FavoriteListItem value) {
            return value.getNickname() != null ? value.getNickname() : "未知联系人";
        }

        // 获取安全的最后消息（处理null情况）
        private String getSafeLastMessage(FavoriteListItem value) {
            return value.getLastMessage() != null ? value.getLastMessage() : "暂无消息";
        }

        // 设置时间标签（处理时间可能为0的情况）
        private void setTimeLabel(FavoriteListItem value) {
            if (value.getLastMessageTime() <= 0) {
                timeLabel.setText("");
                return;
            }

            Date messageTime = new Date(value.getLastMessageTime());
            Date now = new Date();
            if (now.getTime() - messageTime.getTime() < 24 * 60 * 60 * 1000) {
                timeLabel.setText(timeFormat.format(messageTime));
            } else {
                timeLabel.setText(dateFormat.format(messageTime));
            }
        }
    }
}